package com.zprmb.udzt.activity;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.zprmb.udzt.BaseActivity;
import com.zprmb.udzt.BbtApplication;
import com.zprmb.udzt.CustomDialog_view2;
import com.zprmb.udzt.CustomDialog_view3;
import com.zprmb.udzt.R;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.view.WebViewDialog;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@SuppressLint("SetJavaScriptEnabled")
public class NewV6WebviewChild extends BaseActivity {

    private ImageView iv_v4_web_back;
    private TextView tv_v4_web_title;
    private String title;
    private String ref = "";
    private String url;

    String version = "";
    private WebViewDialog dialog;
    private WebView v4_webview;
    private RelativeLayout rl_back;
    //	private ProgressBar bar;
    private boolean back = false;
    private SharedPreferences sha;
    int flag;
    Map<String, String> extraHeaders;
    private int reload = 0;
    private String active_url;

    private int active;
    private ImageView iv_v4_nonetwork;
    String my_flagephone = "0";

    KeyguardManager keyguardManager = (KeyguardManager) BbtApplication.getContext().getSystemService(BbtApplication.getContext().KEYGUARD_SERVICE);
    private CustomDialog_view2.Builder builder2;
    private CustomDialog_view3.Builder builder3;
    private Handler handler2 = null;

    View web_head_view;

    View title_view;
    //下拉刷新
//    private   PullToRefreshScrollView sv;
    View title_view_new;
View view_titlebar;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v6_webviewchild_activity);
        BbtApplication.getInstance().addActvity(this);

        Intent intent = getIntent();
        view_titlebar=findViewById(R.id.view_titlebar);
        view_titlebar.setVisibility(View.GONE);

        title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");

        Log.d(url, "44444444444444");

//        url = intent.getStringExtra("url");
        ref = getShare().getString("usercode", "");
        active = intent.getIntExtra("active", 0);
        active_url = intent.getStringExtra("active_url");
        dialog = new WebViewDialog(this);

        sha = getSharedPreferences("config", MODE_PRIVATE);
        version = getAppVersion();

        initView();
        initData();


        handler2 = new Handler();
        flag = getIntent().getIntExtra("flag", 0);
//		 v4_webview.loadUrl(url+getURLToken());
        Log.d(url, "9999999999999999999999");

        v4_webview.loadDataWithBaseURL(null, url, "text/html", "utf-8", null);


    }


    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if (active == 1) {
            active = 0;
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        BbtApplication.getInstance().removeActvity(this);
        dialog.dismiss();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LogUtils.e(NewV6WebviewChild.this, v4_webview.canGoBack() + "");

            NewV6WebviewChild.this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void initData() {
        extraHeaders = new HashMap<String, String>();
//        extraHeaders.put("token", getToken());
        v4_webview.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("banner_url", url);
                if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {


                    if (url.contains("redirect")) {

                        mpleaseLogin(NewV6WebviewChild.this, 1, 1, 1);
                    } else {

                        if (url.contains("newInvestPage")) {
                            NewV6WebviewChild.this.finish();
                        }

                        if (active == 1) {
                            active = 0;
                            v4_webview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    v4_webview.clearHistory();
                                }
                            }, 1000);
                        }
                        Log.e("链接", url);
//						Log.e("ua", v4_webview.getSettings().getUserAgentString());
                        if (TextUtils.isEmpty(url)) {
                            NewV6WebviewChild.this.finish();
                        } else {
                            view.loadUrl(url);
                        }


                    }


                    return true;
                }

                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub

                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedSslError(WebView arg0, SslErrorHandler arg1,
                                           com.tencent.smtt.export.external.interfaces.SslError arg2) {
                // TODO Auto-generated method stub
//				super.onReceivedSslError(arg0, arg1, arg2);
                arg1.proceed();

            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              String url) {
                // TODO Auto-generated method stub
//		Log.e("header_ss", request.getRequestHeaders().toString());
                WebResourceResponse response = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    response = super.shouldInterceptRequest(view, url);

                    if (url.contains("forapp=1")) {


                        if (url.contains(".css")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.length());
//       			Log.e("css", murl);
                                response = new WebResourceResponse("text/css", "UTF-8", getAssets().open("css" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (url.contains(".png")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.length());
//          	Log.e("png", murl);
                                response = new WebResourceResponse("image/png", "UTF-8", getAssets().open("image/" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (url.contains(".js")) {
                            try {
                                String murl = url.substring(url.lastIndexOf("/") + 1, url.length());
//             	  Log.e("css", "有");
                                response = new WebResourceResponse("application/x-javascript", "UTF-8", getAssets().open("public_js/" + murl));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                return response;
//	return super.shouldInterceptRequest(view, url);
            }

        });
        v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);


        // 重新设置websettings WebSettings s = wb.getSettings();
        // s.setBuiltInZoomControls(true);
        // s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setBlockNetworkImage(false);
        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(NewV6WebviewChild.this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        // This next one is crazy. It's the DEFAULT location for your app's
        // cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();
        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");
        if (v4_webview.getX5WebViewExtension() != null) {
            v4_webview.getX5WebViewExtension().setVerticalTrackDrawable(null);
        }
    }


    String amount = "";
    String amount1 = "";
    String time1 = "";
    String time2 = "";
    String time3 = "";
    String jsonObject = "";
    String url2;


    private final String ACTION_NAME = "发送广播";

    private final String ACTION_NAME2 = "详情页面的跳转";

    public class JsInterfaces {
        private Context mContext;


        public JsInterfaces(Context mContext) {
            super();
            this.mContext = mContext;

        }

        //转入 连连
        @JavascriptInterface
        public void jumpWeb(String couponId, String orderId, String comment) {
//            NewV6WebviewChild.this.finish();
//            Toast.makeText(mContext, couponId, Toast.LENGTH_SHORT).show();

//            orderId comment
//            startActivity(new Intent(NewV6WebviewChild.this,LoginActivity.class));
            Log.d("3333333333333", couponId);
            Log.d("3333333333333", orderId);
            Log.d("3333333333333", comment);
            if (orderId.contains("失败")) {
                Intent intent = new Intent(NewV6WebviewChild.this, FailYueActivity.class);
                intent.putExtra("comment", orderId);
                startActivity(intent);
                finishActivity();
                Intent mIntent = new Intent(ACTION_NAME);
                mIntent.putExtra("yaner", "发送广播，相当于在这里传送数据");
                //发送广播
                sendBroadcast(mIntent);
                Intent mIntent2 = new Intent(ACTION_NAME2);
                mIntent2.putExtra("yaner", "发送广播，相当于在这里传送数据");
                //发送广播
                sendBroadcast(mIntent2);
                NewV6WebviewChild.this.finish();
            } else {


                Log.d("3333333333333", couponId);
                Log.d("3333333333333", orderId);
                Log.d("3333333333333", comment);
                Intent intent = new Intent(NewV6WebviewChild.this, LoadingActivity.class);
                intent.putExtra("orderId", couponId);
                intent.putExtra("comment", orderId);
                intent.putExtra("productType", comment);
                startActivity(intent);
                NewV6WebviewChild.this.finish();
                Intent mIntent = new Intent(ACTION_NAME);
                mIntent.putExtra("yaner", "发送广播，相当于在这里传送数据");
                //发送广播
                sendBroadcast(mIntent);
                Intent mIntent2 = new Intent(ACTION_NAME2);
                mIntent2.putExtra("yaner", "发送广播，相当于在这里传送数据");
                //发送广播
                sendBroadcast(mIntent2);

                V6iNewInvestCoupActivity.instance.finish();
                NewV6WebviewChild.this.finish();
            }

//            finish();
        }


        @JavascriptInterface
        public void finishActivity() {

            NewV6WebviewChild.this.finish();
        }

        @JavascriptInterface
    public void finish(int type) {

            Log.e("type", "type=" + type);
            NewV6WebviewChild.this.finish();


        }


    }


    @Override
    protected void onRestart() {
        super.onRestart();
    }


    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.e("进度", newProgress + "");
            Log.d("33333333333333333", url);
            if (newProgress == 100) {
                dialog.dismiss();
            } else {
                if (dialog.isShowing() == false & !NewV6WebviewChild.this.isFinishing()) {
                    dialog.show();
                }

            }


            super.onProgressChanged(view, newProgress);

        }


        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.e("console", "[" + consoleMessage.messageLevel() + "] " + consoleMessage.message() + "(" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + ")");
            return super.onConsoleMessage(consoleMessage);
        }
    };


    private ImageView img_share;

    private void initView() {
        iv_v4_web_back = (ImageView) findViewById(R.id.img_back);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        web_head_view = findViewById(R.id.web_head_view);
        img_share = (ImageView) findViewById(R.id.img_share);
        web_head_view.setVisibility(View.GONE);
        tv_v4_web_title = (TextView) findViewById(R.id.tv_title);
//		bar = (ProgressBar) findViewById(R.id.myProgressBar);

        try {

            if (url.contains("currentDetail")) {
                tv_v4_web_title.setText("智投宝");
            } else if (url.contains("myNewInvest")) {
                tv_v4_web_title.setText("优享计划");
            } else if (url.contains("fundRecord")) {
                tv_v4_web_title.setText("资金流水");
            } else if (url.contains("myVoucher")) {
                tv_v4_web_title.setText("我的抵扣券");
            } else if (url.contains("myCoupon")) {
                tv_v4_web_title.setText("我的加息券");
            } else if (url.contains("myExperience")) {
                tv_v4_web_title.setText("我的体验金");
            } else if (url.contains("giftcard")) {
                tv_v4_web_title.setText("我的红包");
            } else if (url.contains("inviteFriends")) {
                tv_v4_web_title.setText("我的邀请");
            } else if (url.contains("accountCenter")) {
                tv_v4_web_title.setText("个人中心");
            } /*else if (url.contains("newInvestPage")) {
                NewV6WebviewChild.this.finish();
            }*/ else {
                tv_v4_web_title.setText("个人中心");

            }

        } catch (Exception e) {

        }


        iv_v4_nonetwork = (ImageView) findViewById(R.id.iv_v4_nonetwork);
        rl_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
              /*  if (v4_webview.canGoBack()) {
//                    v4_webview.goBack();
                } else {
                    finish();
                }*/
                NewV6WebviewChild.this.finish();
            }
        });


        iv_v4_web_back.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
               /* if (v4_webview.canGoBack()) {
                    v4_webview.goBack();
                } else {
                    finish();
                }*/
                finish();
            }
        });

        tv_v4_web_title.getPaint().setFakeBoldText(true);

        v4_webview = (WebView) findViewById(R.id.v4_webview);
        title_view = findViewById(R.id.title_view);
        title_view_new = findViewById(R.id.title_view_new);
        title_view_new.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                NewV6WebviewChild.this.finish();
            }
        });

        if (!network()) {
            v4_webview.setVisibility(View.GONE);
            web_head_view.setVisibility(View.GONE);
            iv_v4_nonetwork.setVisibility(View.VISIBLE);
            tv_v4_web_title.setVisibility(View.VISIBLE);
            title_view.setVisibility(View.VISIBLE);
            img_share.setVisibility(View.GONE);
        } else {
            v4_webview.setVisibility(View.VISIBLE);
            web_head_view.setVisibility(View.GONE);
            iv_v4_nonetwork.setVisibility(View.GONE);
            tv_v4_web_title.setVisibility(View.GONE);
            title_view.setVisibility(View.VISIBLE);
        }
        iv_v4_nonetwork.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!network()) {
                    iv_v4_nonetwork.setVisibility(View.VISIBLE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                    v4_webview.setVisibility(View.GONE);
                    title_view.setVisibility(View.VISIBLE);

                    web_head_view.setVisibility(View.GONE);
                    Toast.makeText(NewV6WebviewChild.this, "当前无网络", Toast.LENGTH_SHORT).show();
                } else {
                    iv_v4_nonetwork.setVisibility(View.GONE);//加载成功的话，则隐藏掉显示正在加载的视图，显示加载了网页内容的WebView

                    v4_webview.setVisibility(View.VISIBLE);
                    title_view.setVisibility(View.VISIBLE);
                    web_head_view.setVisibility(View.GONE);
//                    initData();
                    v4_webview.reload();
                    initData();
                }

            }
        });

    }


}
